/**
 * 生成随机扁平化结构树的函数
 * @param {number} n - 生成的节点数
 * @returns {Object[]} - 返回一个包含所有节点的数组，每个节点都有一个唯一的id和一个pid
 */
export function generateRandomTree(n) {
  const tree = [];
  let id = 1;
  let pid = null;
  for (let i = 0; i < n; i++) {
    const node = {
      id: id++,
      pid: pid
    };
    tree.push(node);
    if (Math.random() < 0.5 && pid !== null) {
      pid = node.id;
    } else {
      const randomIndex = Math.floor(Math.random() * i);
      pid = tree[randomIndex].id;
    }
  }
  return tree;
}

function getParentData(data = [], item) {
  let pData = null
  for (let el of data) {
    if (el.id === item.pid) {
      pData = el;
      break;
    } else if (Array.isArray(el.children) && el.children.length > 0) {
      pData = getParentData(el.children, item)
      if (pData) break;
    }
  }
  return pData;
}

/**
 * 递归实现数组转树
 */
export function arrayToTreeByRecursion(data = []) {
  let result = [];
  data.forEach((item) => {
    let pData = getParentData(result, item)
    if (pData) {
      pData.children.push({ ...item, children: [] })
    } else {
      result.push({ ...item, children: [] })
    }
  })
  return result;
}

/**
 * 递归的方式把树转换为数组
 * @param {array} tree 树结构的数组
 * @returns 
 */
export function treeToArrayByRecursion(tree) {
  let result = [];
  tree.forEach((item) => {
    let { children, ...prop } = item;
    result.push(prop);
    if (Array.isArray(children) && children.length > 0) {
      result.push(...treeToArrayByRecursion(children))
    }
  })
  return result
}



/**
 * 不递归实现数组转树
 */
export function arrayToTreeByMap(items) {
  let result = [];
  let itemsMap = {};
  items.forEach(item => {
    let { id, pid } = item;
    if (!itemsMap[id]) {
      itemsMap[id] = {
        children: []
      }
    }

    itemsMap[id] = {
      ...item,
      children: itemsMap[id].children
    }
    let treeItem = itemsMap[id];



    if (pid === null) {
      result.push(treeItem);
    } else {
      if (!itemsMap[pid]) {
        itemsMap[pid] = {
          children: []
        }
      }
      itemsMap[pid].children.push(treeItem)
    }
  })
  return result;
}

const arr = [
  { id: 1, name: 'a', pid: null },
  { id: 7, name: 'g', pid: 3 },
  { id: 2, name: 'b', pid: 1 },
  { id: 3, name: 'c', pid: 1 },
  { id: 4, name: 'd', pid: 2 },
  { id: 5, name: 'e', pid: 2 },
  { id: 6, name: 'f', pid: 3 },

];
